const { SuccessModel, ErrorModel } = require("../../model/resModel");
const { getList, getDetail, createNewManager, updateManager, deleteManager, managerLogin } = require('../../controllers/admin/manager');

const handleManagerRoute = (req, res) => {
    const method = req.method;
    const id = req.query.id;
    const managerData = req.body;

    //新建管理员
    if (method === 'POST' && req.path === '/api/manager/new') {
        const newManagerDataPromise = createNewManager(managerData);
        return newManagerDataPromise.then(newManagerData => {
            return new SuccessModel(newManagerData);
        })
        
    }

    //删除管理员
    if (method === 'POST' && req.path === '/api/manager/delete') {
        const deletedManagerPromise = deleteManager(id);
        return deletedManagerPromise.then(deletedManagerData => {
            if (deletedManagerData) {
                return new SuccessModel(`删除管理员${id}成功`);
            } else {
                return new ErrorModel('删除失败');
            }
        })
        
    }

    //更新管理员
    if (method === 'POST' && req.path === '/api/manager/update') {
        const updatedManagerPromise = updateManager(id, managerData);
        return updatedManagerPromise.then(updatedManagerData => {
            if (updatedManagerData) {
                return new SuccessModel('更新管理员成功！！！');
            } else {
                return new ErrorModel('更新管理员失败');
            }
        })
        
    }

    //管理员登录
    if (method === 'POST' && req.path === '/api/manager/login') {
        const managerAccount = managerData.managerAccount;
        const password = managerData.password;
        const managerloginPromise = managerLogin(managerAccount, password);
        return managerloginPromise.then(loginResult => {
            if (!loginResult[0]) {
                return new SuccessModel(null);
            }
            if (loginResult[0].mng_password == password) {
                return new SuccessModel({
                    managerId: loginResult[0].mng_id,
                    managerAccount: loginResult[0].mng_account,
                    managerAvatar:loginResult[0].mng_avatar
                }, 'true');
            }
            return new SuccessModel(false);
        });

    }

    //获取管理员列表
    if (method === 'GET' && req.path === '/api/manager/list') {
        const listDataPromise = getList();
        return listDataPromise.then(listData => {
            return new SuccessModel(listData);
        });
    }

    //获取管理员详情
    if (method === 'GET' && req.path === '/api/manager/detail') {
        const detailDataPromise = getDetail(id);
        return detailDataPromise.then(detailData => {
            return new SuccessModel(detailData[0]);
        })
    }
}

module.exports = handleManagerRoute;